from asyncio import exceptions

from elasticsearch import Elasticsearch, helpers
import json

# 初始化Elasticsearch客户端
es = Elasticsearch([{'host': '127.0.0.1', 'port': 9200}])


def create_index_case(index_name):
    settings = {
        "settings": {
            "index": {
                "number_of_shards": 1,
                "number_of_replicas": 1,
                "analysis": {
                    "analyzer": {
                        "default": {
                            "tokenizer": "ik_max_word"
                        }
                    }
                }
            }
        },
        "mappings": {
            "properties": {
                "case_name": {"type": "text"},
                "case_number": {"type": "text"},
                "case_reason": {"type": "text"},
                "case_type": {"type": "text"},
                "case_type_code": {"type": "keyword"},
                "court": {"type": "text"},
                "full_text": {"type": "text"},
                "judgment_date": {"type": "text"},
                "legal_basis": {"type": "text"},
                "original_link": {"type": "keyword"},
                "parties": {"type": "text"},
                "publication_date": {"type": "text"},
                "region": {"type": "text"},
                "source": {"type": "keyword"},
                "trial_procedure": {"type": "text"}
            }
        }
    }
    try:
        if not es.indices.exists(index=index_name):
            es.indices.create(index=index_name, body=settings)
            print(f"Index {index_name} created successfully.")
        else:
            print(f"Index {index_name} already exists.")
    except exceptions.RequestError as e:
        print(f"An error occurred: {e}")


# 创建索引
def create_index_law(index_name):
    index_body = {
        "settings": {
            "analysis": {
                "analyzer": {
                    "ik_max_analyzer": {
                        "type": "custom",
                        "tokenizer": "ik_max_word"
                    },
                    "ik_smart_analyzer": {
                        "type": "custom",
                        "tokenizer": "ik_smart"
                    }
                }
            }
        },
        "mappings": {
            "properties": {
                "law_name": {
                    "type": "text",
                    "analyzer": "ik_smart_analyzer"
                },
                "volume": {
                    "type": "text",
                    "analyzer": "ik_smart_analyzer"
                },
                "subvolume": {
                    "type": "text",
                    "analyzer": "ik_smart_analyzer"
                },
                "chapter": {
                    "type": "text",
                    "analyzer": "ik_smart_analyzer"
                },
                "section": {
                    "type": "text",
                    "analyzer": "ik_smart_analyzer"
                },
                "article_number": {
                    "type": "keyword"
                },
                "article_text": {
                    "type": "text",
                    "analyzer": "ik_max_analyzer",
                    "search_analyzer": "ik_smart_analyzer"
                }
            }
        }
    }
    # 检查索引是否已存在
    if es.indices.exists(index=index_name):
        print(f"Index {index_name} already exists.")
    else:
        # 创建索引
        response = es.indices.create(index=index_name, body=index_body)
        if 'acknowledged' in response:
            if response['acknowledged'] == True:
                print(f"Index {index_name} created successfully.")
        else:
            print("Error creating index:", response)


def delete_index(index):
    if es.indices.exists(index=index):
        response = es.indices.delete(index=index)
        print("Index deleted:", response)
    else:
        print("Index does not exist.")


def import_data(es, index_name, file_name):
    with open(file_name, 'r', encoding='utf-8') as f:
        actions = []
        for line in f:
            doc = json.loads(line)
            action = {
                "_index": index_name,
                "_source": doc
            }
            actions.append(action)
        helpers.bulk(es, actions)


# 删除索引
delete_index("case_index_1")
delete_index("laws_index")
# 创建索引
create_index_case("case_index_1")
create_index_law("laws_index")

# 导入数据
import_data(es, "case_index_1", "case_index.json")
import_data(es, "laws_index", "laws_index.json")

print("successfully!")
